<template>
  <div>
    <h1 class="my-4 px-4 text-4xl font-semibold">编辑文章</h1>
    <PostForm ref="form" @success="onSuccess" :is-fetching="isFetching" />
  </div>
</template>
<script setup lang="ts">
import { ApiResponse, useApiFetch } from "@/composables/useApiFetch";
import { SubmissionContext } from "vee-validate";
import PostForm from "@/components/PostForm.vue";
import { useRouteParamsWith } from "@/composables/useRouteParamsWith";

const route = useRoute();
const postId = useRouteParamsWith("id");
const form = ref<InstanceType<typeof PostForm>>();
// 获取文章信息
const { data: postData, execute } = useApiFetch(
  computed(() => `/user/posts/${postId.value}`),
  { refetch: true },
).json<ApiResponse>();
watch(postData, (data) => {
  if (data?.success) {
    // 异步设置表单初始值
    form.value?.resetForm({ values: data.object });
    // form.value?.setValues(data.object);
  }
});
onActivated(() => {
  if (route.params.id) {
    execute();
  }
});

// 编辑
const url = computed(() => `/user/posts/${postId.value}`);
const { isFetching, data, put } = useApiFetch<ApiResponse>(url, {
  immediate: false,
});

const router = useRouter();
const onSuccess = async (values: any, { resetForm }: SubmissionContext) => {
  // 上传图片需要使用formData
  const formData = new FormData();
  Object.entries(values).forEach(([key, value]) => {
    if (value instanceof File) formData.append(key, value, value.name);
    else formData.append(key, value as string);
  });
  await put(formData).json().execute();
  if (data.value?.success) {
    // console.log(data.value);
    // 重置表单
    resetForm();
    // 跳转到我的博客
    router.push({ name: "my.index" });
  }
};
</script>
